package com.dkt.blogboot.util.blogUserEs;

import org.elasticsearch.client.IndicesClient;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.client.indices.CreateIndexRequest;
import org.elasticsearch.client.indices.GetIndexRequest;
import org.elasticsearch.common.xcontent.XContentType;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

@Component
public class EsIndexCreator implements CommandLineRunner {
    @Autowired
    private RestHighLevelClient restHighLevelClient;
    @Override
    public void run(String... args) throws Exception {
        IndicesClient indicesClient = restHighLevelClient.indices();
        GetIndexRequest getRequest = new GetIndexRequest( "user_reg_es");
        boolean exists = indicesClient.exists(getRequest, RequestOptions.DEFAULT);
        if (exists){
            System.out.println("user_reg_es索引库已存在，不再重复创建");
        }else {
            CreateIndexRequest request = new CreateIndexRequest("user_reg_es");
            request.source(MAPPING_TEMPLATE, XContentType.JSON);
            indicesClient.create(request, RequestOptions.DEFAULT);
        }
    }
    public static final String MAPPING_TEMPLATE ="{\n" +
            "  \"mappings\": {\n" +
            "    \"properties\": {\n" +
            "      \"id\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      },\n" +
            "      \"username\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"password\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"nickname\":{\n" +
            "        \"type\": \"keyword\"\n" +
            "      },\n" +
            "      \"status\":{\n" +
            "        \"type\": \"integer\"\n" +
            "      }\n" +
            "    }\n" +
            "  }\n" +
            "}";
}
